//
//  LoginSMSViewModel.swift
//  casdon_swiftUI
//
//  Created by ww on 2025/4/16.
//

import Foundation
import ThingSmartBaseKit
import Combine

class LoginSMSViewModel: ObservableObject{
    @Published var account: String = ""
    @Published var code: [String] = Array(repeating: "", count: 6)
    @Published var currentCodeIndex = 0
    @Published var isLoading = false
    @Published var isAgreed = false
    @Published var sendSuccess = false
    @Published var sendStatusTrigger = UUID()
    @Published var showToast = false
   
//    var codeInputVM = VerificationCodeView
    
    var toastMsg = ""
    
    var cancellables = Set<AnyCancellable>()
    private let codeSubject = CodeNotificationBridge.shared.codeSubject
    
    
    private lazy var wechatLoginFlow =  WeChatLoginFlow()
    
    // 默认初始化
    init() {}
    
    // 带账号参数的初始化
    init(account: String) {
        self.account = account
    }
    
    func resetStatus()
    {
        self.isLoading = false
        self.sendSuccess = false
        self.showToast = false
    }
    
    func wechatLogin()
    {
        self.wechatLoginFlow.start()
            .sink(receiveCompletion: {completion in
            }, receiveValue: { result in
                Logger.log(.debug,message: "微信登录成功", tag: .login)
            }).store(in: &cancellables)
        
    }
    
    var isAccountValid: Bool {
        account.isEmail || account.isPhoneNum
    }
    
    func requestCode() {
        isLoading = true
        CDGetVerifyCodeStep().execute(.init(account: account, type: .notRegister))
            .receive(on: DispatchQueue.main)
            .sink(receiveCompletion: {[weak self] completion in
                switch completion {
                case .finished:
                    print("119615, 获取验证码 finished")
                    self?.isLoading = false
                case .failure(let error):
                    print("119615, 获取验证码 error: \(error)")
                    self?.showToast = true
                    self?.isLoading = false
                    self?.toastMsg = error.localizedDescription
                }
            }, receiveValue: {[weak self] userInfo in
                print("119615, 获取验证码 value: \(userInfo)")
                self?.isLoading = false
                self?.sendSuccess = true
            })
            .store(in: &cancellables)
    }
    
}
